const ws = require('nodejs-websocket');
const log = require('../utils/log');
const msgCfg = require('../common/MsgCfg');
const loginModel = require('./loginModel');
const CmdLogin = require('./proto/CmdLogin');
const redisBase = require('../common/RedisBase');

class loginMessageMgr{
    constructor(){

    }

    static getInstance(){
        if(!loginMessageMgr.instance){
            loginMessageMgr.instance = new loginMessageMgr();
            return loginMessageMgr.instance;
        }else{
            return loginMessageMgr.instance;
        }
    }

    connectServer(port){
        log.warn('=======connectServer==login=========',port);
        let websocket = ws.createServer((client)=>{
            log.info('====收到客户端发送的消息=====');

            //收到的是json 数据
            client.on('text',(result)=>{
                log.info('====收到客户端发送的消息=text=====');
                this.proto_type = msgCfg.PROTOTYPE.PROTO_JSON;
                this.decodeJson(result,client);
            });

            client.on('error',(err)=>{
                log.error('=======链接出现错误=========');
            });

            client.on('close',(code,reason)=>{
                log.error('=======链接断开登录服务 用户uid = ', client.pathname);
            });

            client.on('connection',(conn)=>{
                log.error('=======connection=========');
            });

            client.on('listening',(conn)=>{
                log.error('=======listening=========');
            })
        })
        websocket.listen(port);
        console.log('服务端正在运行');
    }

    //解析json协议
    decodeJson(result,client){
        let msg = JSON.parse(result);
        let type = msg.type
        let data = msg.data;
        log.info('======decodeJson========',type,data);
        this.recvMessage(type,data, client);
    }

    //接受客户端收到的消息
    recvMessage(ctype, data, client){
        log.info('=========recvMessage==========',ctype,data.userOpId);
        switch (ctype) {
            case CmdLogin.LoginReq:
                this.onLoginReq(data,ctype,client);
                break;
            default:
                break;
        }
    }

    sendMessage(data, client){
        if(this.proto_type === msgCfg.PROTOTYPE.PROTO_BINARY){
            log.error('======sendMessage binary=======',data);
            client.sendBinary(data);
        }else if(this.proto_type === msgCfg.PROTOTYPE.PROTO_JSON){
            log.warn('======sendMessage JSON=======',data.type);
            client.send(JSON.stringify(data));
        }
    }

    async addUserToRedis(user){
        let uid = user.userId;
        let list = await redisBase.getUserList();
        for (let i = 0; i < list.length; i++) {
            if(list[i].userId === uid){
                return;
            }
        }
        await redisBase.setUserInRedis(user);
    }

    //搜到登录消息
    async onLoginReq(data,type,client){
        var uid = data.userOpId;
        var uname = data.name;
        var uavator = data.avator;

        client.pathname = uid;

        log.error('=======onLoginReq===========',uid);
        //判断redis里面是否存在这个用户
        let userRedis = await redisBase.getUserInfo(uid);
        log.info('=======判断redis里面是否存在这个用户===========',userRedis);
        if(userRedis && Object.keys(userRedis).length > 0){
            log.warn("======redis 里面存在这个用户========",userRedis.userId);
            this.onLoginSuccess(userRedis,type,client);
        }else{
            log.warn('=====redis里面没有这个用户=======');
            // let uid = 'web_ti6lrZGZ';
            let userMysql = await loginModel.searchInMysql(uid);
            log.info('=====mysql里面没有这个用户1=======',userMysql);
            if(userMysql && userMysql.length > 0){
                log.warn("======mysql 里面存在这个用户========",userMysql);
                //将数据存到redis
                log.info("=====将数据存到redis ========");
                await this.addUserToRedis(userMysql[0])
                log.info("=====返回结果1 ========");
                //返回结果
                this.onLoginSuccess(userMysql[0],type,client);
            }else{
                log.warn("=====mysql 里面不存在这个用户========",userMysql);
                //插入一条数据到userInfo 白哦
                log.info("=====插入一条数据到userInfo ========");
                let res = await global.loginSerMgr.loginDb.insetUserToMsql(uid, uname, uavator,1);
                //获取用户数据
                log.info("=====获取用户数据 ========");
                let _user = loginModel.setNewUserData(uid, uname, uavator);
                //将数据存到redis
                log.info("=====将数据存到redis ========");
                await this.addUserToRedis(_user)

                //返回结果
                log.info("=====返回结果2 ========");
                this.onLoginSuccess(_user,type,client);
            }
        }
        log.warn("=============onLoginReq end=================")
        redisBase.closeRedis();
    }

    onLoginSuccess(user,type,client){
        log.info("=========onLoginSuccess=========",user.userId);
        if(this.proto_type === msgCfg.PROTOTYPE.PROTO_BINARY){
            let buf = loginModel.login_ses_success_sinary(user,type);
            log.info('========bufMsg2========',buf);
            this.sendMessage(buf, client);
        }else if(this.proto_type === msgCfg.PROTOTYPE.PROTO_JSON){
            let buf = loginModel.login_ses_success_json(user,type);
            this.sendMessage(buf, client);
        }
    }
}

module.exports = loginMessageMgr.getInstance();